package icu.zhhll.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @author zh
 * @date 2023/8/14 16:15
 */
public class TraceFilter extends OncePerRequestFilter {

    // 是否开启
    private boolean enable;

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isBlank(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (StringUtils.isBlank(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip)) {
            ip = request.getRemoteAddr();
        }
        String[] ips = ip.split(",");
        return ips[0];
    }

    @Override
    public void initFilterBean() {
        this.enable = Boolean.parseBoolean(getFilterConfig().getInitParameter("enable"));
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (this.enable) {
            // 记录requestId
            MDC.put("requestId", UUID.randomUUID().toString());
            MDC.put("ip", getIpAddr(request));
            filterChain.doFilter(request, response);
        }
    }
}
